package com.example.myapplication.Teacher;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.NetworkOnMainThreadException;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.example.myapplication.Data.UserData;
import com.example.myapplication.R;
import com.example.myapplication.http.ResponseBody;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.Util;

public class TeacherAddActivity extends AppCompatActivity {
    private static final int PICK_IMAGE_REQUEST = 1;
    private static final int REQUEST_IMAGE_CAPTURE = 2;
    private ImageView ivCourseImage;
    private String filePath;
    private BottomSheetDialog bottomSheetDialog;
    private RelativeLayout tvAlbum;
    private RelativeLayout tvCamera;
    private ImageView ivAvatar;
    private EditText etCollegeName;
    private String collegeName;
    private EditText etCourseName;
    private String courseName;
    private EditText etEndDate;
    private String endDate;
    private EditText etCourseDescription;
    private String courseDescription;
    private EditText etStartDate;
    private String startDate;
    private Button btnAddCourse;
    private final Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teacher_add);
        initView();
        ivCourseImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View bottomSheetView = getLayoutInflater().inflate(R.layout.edit_picture, null);
                bottomSheetDialog.setContentView(bottomSheetView);
                tvAlbum = bottomSheetView.findViewById(R.id.tv_album);
                tvCamera = bottomSheetView.findViewById(R.id.tv_camera);
                Album(); // 相册按钮
                Camera(); // 照相按钮
                bottomSheetDialog.show();
            }
        });
        btnAddCourse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initData();
                post();
            }
        });
    }

    private void initData() {
        collegeName = etCollegeName.getText().toString();
        courseName = etCourseName.getText().toString();
        endDate = etEndDate.getText().toString();
        courseDescription = etCourseDescription.getText().toString();
        startDate = etStartDate.getText().toString();
    }

    private void initView() {
        ivCourseImage = findViewById(R.id.ivCourseImage);
        bottomSheetDialog = new BottomSheetDialog(this); // 底部弹窗

        etCollegeName = findViewById(R.id.etCollegeName);
        etCourseName = findViewById(R.id.etCourseName);
        etEndDate = findViewById(R.id.etEndDate);
        etCourseDescription = findViewById(R.id.etCourseDescription);
        etStartDate = findViewById(R.id.etStartDate);
        btnAddCourse = findViewById(R.id.btnAddCourse);
    }

    private void post() {
        new Thread(() -> {
            UserData userData = (UserData) getIntent().getSerializableExtra("userData");
            // URL路径
            String url = "http://47.107.52.7:88/member/sign/course/teacher";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            // 请求体
            // PS.用户也可以选择自定义一个实体类，然后使用类似fastjson的工具获取json串
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("collegeName", collegeName);
            bodyMap.put("courseName", courseName);
            bodyMap.put("coursePhoto", filePath);
            bodyMap.put("endTime", endDate);
            bodyMap.put("introduce", courseDescription);
            bodyMap.put("realName", userData.getRealName());
            bodyMap.put("startTime", startDate);
            bodyMap.put("userId", userData.getId());
            bodyMap.put("userName", userData.getUserName());
            // 将Map转换为字符串类型加入请求体中
            String body = gson.toJson(bodyMap);

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            // 请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                // 发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            } catch (NetworkOnMainThreadException ex) {
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            // TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            // TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>() {}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body, jsonType);
            Log.d("info", dataResponseBody.toString());

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(dataResponseBody.getCode()==200){
                        Toast.makeText(TeacherAddActivity.this, "添加课程成功", Toast.LENGTH_LONG).show();
                        finish();
                    } else{
                        Toast.makeText(TeacherAddActivity.this, dataResponseBody.getMsg(), Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    };

    private void Album() {
        tvAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 启动相册选择器
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, PICK_IMAGE_REQUEST);
            }
        });
    }

    private void Camera() {
        tvCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 创建保存照片的文件
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                if (photoFile != null) {
                    Uri photoURI = FileProvider.getUriForFile(TeacherAddActivity.this,
                            "com.example.myapplication.fileprovider",
                            photoFile);

                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                }
            }
        });
    }

    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File imageFile = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );
        filePath = imageFile.getAbsolutePath();
        return imageFile;
    }

    private void uploadImage() {
        if (filePath != null) {
            File file = new File(filePath);

            // URL路径
            String url = "http://47.107.52.7:88/member/sign/image/upload";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            // 创建一个多部分请求体
            MultipartBody.Builder multipartBuilder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);

            MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpeg");
            RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);

            // 添加文件字段
            multipartBuilder.addFormDataPart("file", file.getName(), fileBody);

            RequestBody requestBody = multipartBuilder.build();

            // 创建POST请求
            Request request = new Request.Builder()
                    .url(url)
                    .headers(headers)
                    .post(requestBody)
                    .build();

            OkHttpClient client = new OkHttpClient();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, IOException e) {
                    e.printStackTrace();
                    // 处理上传失败的逻辑
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(TeacherAddActivity.this, "上传失败", Toast.LENGTH_LONG).show();
                        }
                    });
                }

                @Override
                public void onResponse(@NonNull Call call, Response response) throws IOException {
                    String responseBody = response.body().string();
                    Type jsonType = new TypeToken<ResponseBody<Object>>() {}.getType();
                    ResponseBody<Object> dataResponseBody = gson.fromJson(responseBody, jsonType);
                    int code = dataResponseBody.getCode();
                    final String msg = dataResponseBody.getMsg();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (code == 200) {
                                Toast.makeText(TeacherAddActivity.this, msg, Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(TeacherAddActivity.this, "上传失败：" + msg, Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            });
        } else {
            // 文件路径为空，未选择图片
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(TeacherAddActivity.this, "请选择图片", Toast.LENGTH_LONG).show();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            filePath = getRealPathFromURI(selectedImageUri);

            if (filePath != null) {
                ivCourseImage.setImageURI(Uri.fromFile(new File(filePath)));
                uploadImage(); // 上传图片
            } else {
                Toast.makeText(this, "无法获取文件路径", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            ivCourseImage.setImageURI(Uri.fromFile(new File(filePath)));
            uploadImage(); // 上传拍摄的照片
        }
    }

    // 将URI转换为文件路径
    private String getRealPathFromURI(Uri contentUri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
        if (cursor == null) {
            return null;
        }
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String filePath = cursor.getString(column_index);
        cursor.close();
        return filePath;
    }
}

